/**
 * <p/>
 * 实现功能：公司
 * <p/>
 *
 * @author 李艳
 */
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Button, message, Input, Checkbox, Modal } from 'antd';
import SimpleTable from "../../../commons/components/SimpleTable";
import { hide, show } from "../../../configs/SharedReducer";
import { deleteCorp, getAllCorporation, save } from "./CorporationService";
import EditCorporationModal from "./EditCorporationModal";
import { cache, searchListByKeyWithTag } from "../../../commons/utils/CommonUtils";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import PageOperateHoc from "../../../commons/components/PageOperateHoc/index.jsx";
import CheckAuth from "../../../commons/components/CheckAuth/index.jsx";

const Search = Input.Search;
const confirm = Modal.confirm
class CorporationTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            modalVisible: false,
            confirmLoading: false,
            selectedRows: [],
            isAdd: false
        };
    }

    componentWillMount() {
        this.getDataSource()
    }

    onRef = (ref) => {
        this.ref = ref
    };
    getDataSource = () => {
        this.props.show();
        getAllCorporation().then(data => {
            this.setState({ data, selectedRows: [], searchValue: "" })
        }).catch(e => {
        }).finally(() => {
            this.props.hide();
        })
    };

    handleRowSelectChange = (selectedRows) => {
        this.setState({ selectedRows })
    };
    handleModalVisible = (modalVisible, isAdd = this.state.isAdd) => {
        this.setState({ modalVisible, isAdd })
    };
    addClick = () => {
        this.handleModalVisible(true, true)
    };
    editClick = (record) => {
        this.setState({ editData: record });
        this.handleModalVisible(true, false)
    };
    handleSave = () => {
        this.ref.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                let params = {}
                Object.assign(params, values);
                if (this.state.isAdd)
                    delete params.id;//新增时id==="",保存会出错，需删除id
                let tenantCode = "";
                if (cache) {
                    tenantCode = cache.get("Authorization").tenantCode
                } else {
                    if (this.state.editData) {
                        tenantCode = this.state.editData.tenantCode
                    }
                }
                params.tenantCode = tenantCode;
                params.code = tenantCode + "-" + values.code
                this.setState({ confirmLoading: true });
                save(params).then(result => {
                    if (result.status === "SUCCESS") {
                        message.success(result.message ? result.message : "请求成功");
                        //刷新本地数据
                        this.getDataSource();
                      this.setState({ confirmLoading: false, modalVisible: false });
                    } else {
                        message.error(result.message ? result.message : "请求失败");
                      this.setState({ confirmLoading: false });
                    }
                }).catch(e => {
                  this.setState({ confirmLoading: false });
                })
            }
        })
    };
    judgeSelected = () => {
        if (this.state.selectedRows.length === 0) {
            message.error("请选择一行数据！");
            return false
        }
        return true
    };

    handleModalCancel = () => {
        this.handleModalVisible(false)
    };

    handleSearch = (value) => {
        searchListByKeyWithTag(this.state.data, { keyword: value }, ['code', 'name']).then(data => {
            this.setState({ data, searchValue: value })
        })
    };

    deleteClick = (record) => {
        let thiz = this;
        confirm({
          title: "温馨提示",
          content: "删除后不可恢复，是否确定删除？",
            onOk() {
                let params = {};
                params = record.id;
                thiz.props.show();
                deleteCorp(params).then(result => {
                    if (result.status === "SUCCESS") {
                        message.success(result.message ? result.message : "请求成功");
                        //刷新本地数据
                        thiz.getDataSource();
                    } else {
                        message.error(result.message ? result.message : "请求失败");
                    }
                }).catch(e => {
                }).finally(() => {
                    thiz.props.hide();
                })
            }
        });
    };

    render() {
        const columns = [
            {
                title: "操作",
                width: 120,
                dataIndex: "operator",
                render: (text, record, index) => {
                    return (
                        <div className={'row-operator'} onClick={(e) => { e.stopPropagation() }}>
                            <CheckAuth operateCode="BASIC-ZZJG-CORPORATION-EDIT" >
                                <a className={'row-operator-item'} onClick={() => this.editClick(record)}>编辑</a>
                            </CheckAuth>
                            <CheckAuth operateCode="BASIC-ZZJG-CORPORATION-DELETE" >
                                <a className={'row-operator-item'} onClick={() => this.deleteClick(record)}>删除</a>
                            </CheckAuth>
                        </div>
                    )
                }
            },
            {
                title: '代码',
                dataIndex: 'code',
                width: 140
            },
            {
                title: '名称',
                dataIndex: 'name',
                width: 200
            },
            {
                title: 'ERP公司代码',
                dataIndex: 'erpCode',
                width: 100
            },
            {
                title: '本位币货币名称',
                dataIndex: 'baseCurrencyName',
                width: 120
            },
            {
                title: '本位币货币代码',
                dataIndex: 'baseCurrencyCode',
                width: 120
            },
            {
                title: '默认贸易伙伴代码',
                dataIndex: 'defaultTradePartner',
                width: 140
            },
            {
                title: '关联交易贸易伙伴',
                dataIndex: 'relatedTradePartner',
                width: 200
            },
            {
                title: '排序',
                dataIndex: 'rank',
                width: 100,
                render: (text, record, index) => (
                    <div style={{ textAlign: "right" }}>
                        {record.rank}
                    </div>
                ),
                sorter: (a, b) => {
                  return a.rank - b.rank;
                }
            },
            {
                title: '冻结',
                width: 100,
                render: (text, record, index) => (
                    <div style={{ textAlign: "center" }}>
                        <Checkbox checked={record.frozen === true} disabled />
                    </div>
                ),
            }
        ];

        const title = () => {
            return [
                <CheckAuth operateCode="BASIC-ZZJG-CORPORATION-ADD" key="edit" >
                    <Button type={"primary"} style={{ marginRight: '8px' }}
                        onClick={this.addClick}>新增</Button>
                </CheckAuth>
            ]
        };

        //表头搜索框
        const search = () => {
            return [
                <Search
                    key="search"
                    placeholder="输入名称或代码进行查询"
                    onSearch={value => this.handleSearch(value)}
                    style={{ width: 220 }}
                    allowClear
                />
            ]
        };

        return (
            <HeadBreadcrumb>
                <div className={"tbar-table"}>
                    <div className={'tbar-box'}>
                        <div className={'tbar-btn-box'}>{title()}</div>
                        <div className={'tbar-search-box'}>{search()}</div>
                    </div>
                    <SimpleTable
                        rowsSelected={this.state.selectedRows}
                        onSelectRow={this.handleRowSelectChange}
                        data={this.state.searchValue ? this.state.data.filter(item => item.tag === true) : this.state.data}
                        columns={columns}
                    />
                </div>
                {this.state.modalVisible && <EditCorporationModal
                    isAdd={this.state.isAdd}
                    modalVisible={this.state.modalVisible}
                    confirmLoading={this.state.confirmLoading}
                    handleOk={this.handleSave}
                    handleCancel={this.handleModalCancel}
                    onRef={this.onRef}
                    defaultValue={!this.state.isAdd ? this.state.editData ? this.state.editData : {} : {}} />}
            </HeadBreadcrumb>
        )
    }
}

const mapStateToProps = (state) => {
    return {};
};

const mapDispatchToProps = (dispatch) => {
    return {
        show: () => {
            dispatch(show())
        },
        hide: () => {
            dispatch(hide())
        },
    }
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(PageOperateHoc(CorporationTable))



